package com.rbw.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rb.util.NumUtil;
import com.rb.util.StringUtil;
import com.rbw.controller.req.CheckRegUserParam;
import com.rbw.controller.req.EditUserParam;
import com.rbw.controller.req.FavoriteParam;
import com.rbw.controller.req.LoginParam;
import com.rbw.controller.req.RegParam;
import com.rbw.controller.req.ResetPasswordParam;
import com.rbw.controller.req.SendVCodeParam;
import com.rbw.controller.res.BaseResult;
import com.rbw.controller.res.ListResult;
import com.rbw.controller.res.ObjectResult;
import com.rbw.controller.res.model.RTechBean;
import com.rbw.model.TechBean;
import com.rbw.model.UserBean;
import com.rbw.service.UserService;
import com.rbw.service.exception.ServiceException;

@Controller
@RequestMapping("/user")
public class UserController {

	
	@Autowired
	UserService userServiceImpl;

	/**
	 * 发送验证码至手机号或者邮箱
	 * 
	 * @param param
	 * @param error
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/v1/sendVCode")
	@ResponseBody
	public BaseResult sendVCode(@Validated SendVCodeParam param, BindingResult error, HttpServletRequest request,
			HttpServletResponse response) {
		BaseResult result = new BaseResult();

		int type = param.getType();
		int action = param.getAction();
		String username = param.getUsername();

		try {
			boolean flag = userServiceImpl.sendVCode(action, type, username);
			result.setFlag(flag);
		} catch (ServiceException e) {
			result.setServiceException(e);
		}

		return result;
	}

	/**
	 * 检查注册用户名是否合法 type=1，手机号 type=2,邮箱
	 * 
	 * @param param
	 * @param error
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/v1/checkRegUser")
	@ResponseBody
	public BaseResult checkRegUser(@Validated CheckRegUserParam param, BindingResult error, HttpServletRequest request,
			HttpServletResponse response) {
		BaseResult result = new BaseResult();

		int type = param.getType();
		UserBean user = userServiceImpl.existUser(type, param.getUsername());
		result.setFlag(user != null);
		return result;
	}

	/**
	 * 检查登录用户名
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/v1/checkLoginUser")
	@ResponseBody
	public BaseResult checkLoginUser(HttpServletRequest request, HttpServletResponse response) {
		// 参数
		String username = request.getParameter("username");

		BaseResult result = new BaseResult();
		try {
			UserBean user = userServiceImpl.existUser(1, username);
			if (user != null) {
				result.setFlag(true);
			}
		} catch (ServiceException e) {
			result.setFlag(false);
			result.setMsg(e.getServiceMsg());
		}
		return result;
	}

	/**
	 * 登录
	 * 
	 * @param phoneNum
	 * @param password
	 * @return
	 */
	@RequestMapping("/v1/login")
	@ResponseBody
	public BaseResult login(@Validated LoginParam param, BindingResult error, HttpServletRequest request,
			HttpServletResponse response) {
		BaseResult result = new BaseResult();
		if (error.hasErrors()) {
			result.setFlag(false);
			result.setMsg(error.getFieldError().getDefaultMessage());
		}

		try {
			String sessionId = request.getSession().getId();

			UserBean user = userServiceImpl.login(sessionId, param.getUsername(), param.getPassword());
			if (user != null) {
				result.setFlag(true);
			}
		} catch (ServiceException e) {
			result.setFlag(false);
			result.setMsg(e.getServiceMsg());
		}
		return result;
	}

	/**
	 * 注册
	 * 
	 * @param param
	 * @param error
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/v1/reg")
	@ResponseBody
	public BaseResult reg(@Validated RegParam param, BindingResult error, HttpServletRequest request,
			HttpServletResponse response) {
		BaseResult result = new BaseResult();
		if (error.hasErrors()) {
			result.setFlag(false);
			result.setMsg(error.getFieldError().getDefaultMessage());
		}

		String uname = param.getUsername();
		String pwd = param.getPwd();
		String spwd = param.getSubmitPwd();
		String vcode = param.getVcode();
		try {
			String sessionId = request.getSession().getId();
			UserBean user = param.getType() == 1 ? userServiceImpl.regByPhone(sessionId, uname, pwd, spwd, vcode)
					: userServiceImpl.regByEmail(sessionId, uname, pwd, spwd, vcode);
			if (user != null) {
				result.setFlag(true);
			}
		} catch (ServiceException e) {
			result.setFlag(false);
			result.setMsg(e.getServiceMsg());
		}
		return result;
	}
	
	/**
	 * 个人中心获取个人信息页面
	 * @param param
	 * @param error
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/v1/getDetail")
	@ResponseBody
	public ObjectResult<?> getDetail(HttpServletRequest request, HttpServletResponse response) {
		ObjectResult<UserBean> result = new ObjectResult<>();
		UserBean user = (UserBean) request.getAttribute("user");
		result.setData(user);
		return result;
	}
	
	/**
	 * 修改用户信息
	 * @param param
	 * @param error
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/v1/editUser")
	@ResponseBody
	public BaseResult editUser(@Validated EditUserParam param, BindingResult error, HttpServletRequest request,
			HttpServletResponse response) {
		BaseResult result = new BaseResult();
		if (error.hasErrors()) {
			result.setFlag(false);
			result.setMsg(error.getFieldError().getDefaultMessage());
		}
		boolean flag = false;
		try {
			int type = NumUtil.toInt(param.getType(), 0);
			String value = StringUtil.toString(param.getValue(), null);
			String vcode = StringUtil.toString(param.getVcode(), null);
			flag =  userServiceImpl.editUser(request, type, value, vcode);
			result.setFlag(flag);
		} catch (ServiceException e) {
			result.setFlag(false);
			result.setMsg(e.getServiceMsg());
		}
		return result;
	}
	
	/**
	 * 提交需求
	 * 
	 * @param phoneNum
	 * @param password
	 * @return
	 */
	@RequestMapping("/v1/submitRequire")
	@ResponseBody
	public BaseResult submitRequire(String username, String telephone, String content) {
		BaseResult result = new BaseResult();
		String name = StringUtil.toString(username, null);
		if(StringUtil.checkEmpty(name)){
			result.setRescode(BaseResult.fail.getCode());
			result.setMsg("请填写称呼");
			return result;
		}
		String phone = StringUtil.toString(telephone, null);
		String regex = "^1[3|4|5|8]\\d{9}$";  
		if(StringUtil.checkEmpty(phone) || !phone.matches(regex)){
			result.setRescode(BaseResult.fail.getCode());
			result.setMsg("请填写正确的手机号");
			return result;
		}
		if(StringUtil.checkEmpty(content)){
			result.setRescode(BaseResult.fail.getCode());
			result.setMsg("请填写您的需求");
			return result;
		}
		boolean flag = userServiceImpl.submitRequire(username, telephone, content);
		result.setRescode(flag ? BaseResult.success.getCode() : BaseResult.fail.getCode());
		result.setMsg(flag ? BaseResult.success.getMsg() : BaseResult.fail.getMsg());
		return result;
	}
	
	/**
	 * 修改用户密码
	 * @param param
	 * @param error
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/v1/resetPassword")
	@ResponseBody
	public BaseResult resetPassword(@Validated ResetPasswordParam param, HttpServletRequest request,
			HttpServletResponse response) {
		boolean flag = false;
		BaseResult result = new BaseResult();
		try {
			String pwd = StringUtil.toString(param.getPwd(), null);
			String newpwd = StringUtil.toString(param.getNewpwd(), null);
			String snewpwd = StringUtil.toString(param.getSnewpwd(), null);
			flag =  userServiceImpl.resetPassword(request, pwd, newpwd, snewpwd);
			result.setFlag(flag);
		} catch (ServiceException e) {
			result.setFlag(false);
			result.setMsg(e.getServiceMsg());
		}
		return result;
	}
	
	
	/**
	 * 关注或取消关注技术成果
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/v1/favorite")
	@ResponseBody
	public BaseResult favorite(@Validated FavoriteParam param, HttpServletRequest request,
			HttpServletResponse response) {
		boolean flag = false;
		BaseResult result = new BaseResult();
		try {
			String targetId = StringUtil.toString(param.getTargetId(), null);
			int type = param.getType();
			flag =  userServiceImpl.favorite(request, targetId, type);
			result.setFlag(flag);
		} catch (ServiceException e) {
			result.setFlag(false);
			result.setMsg(e.getServiceMsg());
		}
		return result;
	}
	
	/**
	 * 获取用户关注技术成果列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/v1/getFavorites")
	@ResponseBody
	public ListResult<RTechBean> getFavorites(HttpServletRequest request, HttpServletResponse response) {
		String sessionId = request.getSession().getId();
		ListResult<RTechBean> result = new ListResult<RTechBean>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		int page = NumUtil.toInt(request.getParameter("page"), 1);
		int pageSize = NumUtil.toInt(request.getParameter("pageSize"), 10);
		ListResult<TechBean> res = userServiceImpl.getFavorites(sessionId, page, pageSize);
		if (res != null && res.getData() != null) {
			List<RTechBean> list = new ArrayList<>();
			for (TechBean tech : res.getData()) {
				RTechBean rt = new RTechBean();
				rt.setTid(tech.getTid());
				rt.setName(tech.getName());
				rt.setAddress(tech.getAddress());
				rt.setReleaseTime(sdf.format(tech.getReleaseTime()));
//				rt.setLabels(tech.getLabels());
				rt.setOrigin(tech.getOrigin());
				rt.setIndustry(tech.getIndustry());
				rt.setCategory(tech.getCategory());
				rt.setTradeType(tech.getTradeType());
				rt.setContent(tech.getContent());
				rt.setFavoriteState(tech.getFavoriteState());
				list.add(rt);
			}
			result.setData(list);
			result.setTotalSize(res.getTotalSize());
		}
		return result;
	}
}
